<?php

namespace app\admin\model;
use app\common\model\BaseModel;
use think\facade\Cache;

/**
 * 后台用户角色权限
 * Class AdminRole
 * @package app\admin\model
 */
class AdminRole extends BaseModel
{
    protected $name = 'admin_role';

    protected $pk = 'admin_role_id';
    /**
     * 追加字段
     * @var array
     */
    protected $append = [];
    

    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'update_time',
        'create_time'
    ];

    public function getadminMenuIdAttr($value){
        return explode(',',$value);
    }

    /**
     * 关联用户权限菜单表
     * @return \think\model\relation\BelongsTo
     */
    public function AdminAuthorityMenu()
    {
        $module = self::getCalledModule() ?: 'common';
        return $this->BelongsTo("app\\{$module}\\model\\AdminAuthorityMenu");
    }

    // 获取所有角色 
    public function getAll()
    {
        // 角色 
        return $this->withoutField("update_time,create_time",true)->select();
    }

    // 新增角色
    public function add($param){
        if(empty($param['name']))
        {
            $this->error = "必须填写角色名称";
            return false;
        }
        if(empty($param['admin_menu_id']))
        {
            $this->error = "必须选择菜单权限";
            return false;
        }
        try {
            $this->startTrans();
            // 新增
            $this->save($param);
            // 更新清理缓存的角色权限选项
            $this->updateClearCache();
            $this->commit();
            return true;
        } catch (\Throwable $th) {
            $this->rollback();
            //throw $th;
            $this->error = $th->getMessage();
            return false;
        }
    }

    // 编辑角色
    public function edit($param){
        if(empty($param['admin_role_id']))
        {
            $this->error = "缺少权限ID";
            return false;
        }
        if(empty($param['name']))
        {
            $this->error = "必须填写角色名称";
            return false;
        }
        if(empty($param['admin_menu_id']))
        {
            $this->error = "必须选择菜单权限";
            return false;
        }
        try {
            // 将前端返回的数组转换成字符串
            $param['admin_menu_id'] = implode(',',$param['admin_menu_id']);
            // 更新
            $this->exists(true)->save($param);
            
            // 清除旧权限缓存
            Cache::delete('menus_'.$param['admin_role_id']);

            return true;
        } catch (\Throwable $th) {
            //throw $th;
            $this->error = $th->getMessage();
            return false;
        }
    }

    public function remove($admin_role_id){
        // 判断是否超管
        if($admin_role_id == 1)
        {
            $this->error = '无法删除超级管理员角色!';
            return false;
        }
        try {
            $this->startTrans();
            // 查询下当前角色是否存在用户
            if(!(new AdminUser)->where(['admin_role_id'=>$admin_role_id])->value('admin_user_id'))
            {
                // 删除角色
                if($this->where(['admin_role_id'=>$admin_role_id])->delete())
                {
                    // 更新设置表
                    $this->updateClearCache();
                    $this->commit();
                    return true;
                }
            }
            $this->error = "该角色下有其他用户,无法删除";
            $this->rollback();
            return false;
        } catch (\Throwable $th) {
            //throw $th;
            $this->error = $th->getMessage();
            $this->rollback();
            return false;
        }
    }

    // 角色详细
    public function detail($admin_role_id){
        
        try {
            // 查询一遍数据
            $result = $this->findOrFail($admin_role_id);
            // 获取用户权限菜单
            $result['AdminMenu'] = (new AdminMenu)->getRoleAuthorityMenu($result);
            return $result;
        } catch (\Throwable $th) {
            //throw $th;
            $this->error = $th->getMessage();
            return false;
        }
    }

    // 更新设置表里面的缓存参数
    private function updateClearCache(){
        $settingModel = new Setting;
        $cacheList = $settingModel->getItem('cache');
        $cacheList['roles']['child'] = $this->column('name,admin_role_id as value');
        array_unshift($cacheList['roles']['child'],[
            'name'=> '全部',
            'value'=>0
        ]);
        
        $settingModel->edit('cache',$cacheList);
    }
}